* Date: Oct 29, 2024

est clear

* Configuration: Define paths for input data and output file
local inputPath "/path/to/your/input/directory"
local outputFile "/path/to/your/output/directory/thh.tex"

* Set working directory and load dataset 
cd "`inputPath'"
use "household_debt.dta", clear

xtset iso_num year

* Generate GDP growth as a percentage
qui gen GDP_growth = (rgdppc - L.rgdppc) / L.rgdppc * 100

* Calculate debt-to-GDP ratios
qui gen hhdebt2gdp = thh / gdp
qui gen fdebt2gdp = tbus / gdp

* Generate cumulative 3-year household and firm debt growth rates
qui gen cum3hhdebt = (log(L.hhdebt2gdp) - log(L4.hhdebt2gdp)) * 100
qui gen cum3fdebt = (log(L.fdebt2gdp) - log(L4.fdebt2gdp)) * 100

* Generate financial sentiment first-difference
qui gen Finance_sentiment_fd = all_stdscore - L.all_stdscore

* Arrange variables for readability
order iso_num year GDP_growth

* Keep relevant variables and reorder them for easier interpretation
keep iso_num year GDP_growth cum3hhdebt cum3fdebt ERA_coarse2 Finance_sentiment_fd
order iso_num year GDP_growth cum3hhdebt cum3fdebt ERA_coarse2

* Create cumulative 3-year finance sentiment difference
qui gen cum3fs_fd = L.Finance_sentiment_fd + L2.Finance_sentiment_fd + L3.Finance_sentiment_fd

* Define binary indicator for ERA categories (update categories as needed)
qui gen ERA23 = .
replace ERA23 = 1 if ERA_coarse2 == 2 | ERA_coarse2 == 3
replace ERA23 = 0 if ERA_coarse2 == 1

* Regression Models
* Model 1: Full sample analysis with GDP growth, cumulative finance sentiment, and debt-to-GDP growth
xtscc GDP_growth cum3fs_fd cum3hhdebt cum3fdebt, fe
estadd local country_FE "Yes", replace
estadd local year_FE "No", replace
est store m1

* Model 2: Fixed regime analysis, excluding specified countries
xtscc GDP_growth cum3fs_fd cum3hhdebt cum3fdebt if ERA_coarse2 == 1 & !inlist(iso_num,1,7), fe
estadd local country_FE "Yes", replace
estadd local year_FE "No", replace
est store m2

* Model 3: Flexible regime analysis with cumulative 3-year credit growth, excluding specified countries
xtscc GDP_growth cum3fs_fd cum3hhdebt cum3fdebt if ERA23 == 1 & !inlist(iso_num,1,7), fe
estadd local country_FE "Yes", replace
estadd local year_FE "No", replace
est store m3

* Export results to a LaTeX file or other output format
esttab m* using "`outputFile'", replace ///
    compress nogap b(%6.2f) se(%6.2f) scalars(N country_FE year_FE) star(* 0.1 ** 0.05 *** 0.01) noconstant obslast ///
    addnote("Note: (1) *** p<1\%, ** p<5\%,* p<10\%;")
